{include file="layout/layui_header" /}

<div class="main-content">
    <div class="page-header">
        <h1 class="page-title">个人信息</h1>
        <p class="page-subtitle">查看和编辑您的个人基本信息</p>
    </div>

    <div class="layui-row layui-col-space20">
        <!-- 左侧个人信息卡片 -->
        <div class="layui-col-md8">
            <div class="widget">
                <div class="widget-header">
                    <h2 class="widget-title">基本信息</h2>
                    <div class="widget-actions">
                        <button class="btn-widget" id="editBtn">
                            <i class="layui-icon layui-icon-edit"></i> 编辑信息
                        </button>
                    </div>
                </div>

                <form class="layui-form" id="profileForm" lay-filter="profileForm">
                    <div class="layui-row layui-col-space20">
                        <!-- 用户名 -->
                        <div class="layui-col-md6">
                            <label class="layui-form-label">用户名</label>
                            <div class="layui-input-block">
                                <input type="text" name="username" readonly class="layui-input layui-disabled">
                            </div>
                        </div>

                        <!-- 真实姓名 -->
                        <div class="layui-col-md6">
                            <label class="layui-form-label">真实姓名</label>
                            <div class="layui-input-block">
                                <input type="text" name="real_name" readonly class="layui-input layui-disabled" placeholder="请输入真实姓名">
                            </div>
                        </div>

                        <!-- 邮箱 -->
                        <div class="layui-col-md6">
                            <label class="layui-form-label">邮箱地址</label>
                            <div class="layui-input-block">
                                <input type="email" name="email" readonly class="layui-input layui-disabled" placeholder="请输入邮箱地址">
                            </div>
                        </div>

                        <!-- 手机号 -->
                        <div class="layui-col-md6">
                            <label class="layui-form-label">手机号码</label>
                            <div class="layui-input-block">
                                <input type="text" name="phone" readonly class="layui-input layui-disabled" placeholder="请输入手机号码">
                            </div>
                        </div>

                        <!-- 部门 -->
                        <div class="layui-col-md6">
                            <label class="layui-form-label">所属部门</label>
                            <div class="layui-input-block">
                                <input type="text" name="department" readonly class="layui-input layui-disabled" placeholder="请输入所属部门">
                            </div>
                        </div>

                        <!-- 职位 -->
                        <div class="layui-col-md6">
                            <label class="layui-form-label">职位</label>
                            <div class="layui-input-block">
                                <input type="text" name="position" readonly class="layui-input layui-disabled" placeholder="请输入职位">
                            </div>
                        </div>

                        <!-- 角色 -->
                        <div class="layui-col-md12">
                            <label class="layui-form-label">分配角色</label>
                            <div class="layui-input-block">
                                <input type="text" name="role_names" readonly class="layui-input layui-disabled">
                            </div>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="layui-col-md12" id="actionButtons" style="display: none;">
                            <div class="layui-form-item" style="margin-top: 30px;">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="updateProfile">
                                        <i class="layui-icon layui-icon-ok"></i> 保存修改
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">
                                        <i class="layui-icon layui-icon-close"></i> 取消
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 右侧头像和统计信息 -->
        <div class="layui-col-md4">
            <!-- 头像卡片 -->
            <div class="widget">
                <div class="widget-header">
                    <h2 class="widget-title">头像</h2>
                </div>
                <div style="text-align: center; padding: 20px 0;">
                    <div class="avatar-container" style="position: relative; display: inline-block;">
                        <img id="userAvatar" src="/static/images/default-avatar.svg" 
                             style="width: 120px; height: 120px; border-radius: 50%; border: 3px solid #f0f0f0; object-fit: cover;">
                        <div class="avatar-overlay" style="position: absolute; top: 0; left: 0; width: 120px; height: 120px; 
                             border-radius: 50%; background: rgba(0,0,0,0.5); display: none; align-items: center; 
                             justify-content: center; cursor: pointer; color: white; pointer-events: none;">
                            <i class="layui-icon layui-icon-camera" style="font-size: 24px;"></i>
                        </div>
                        <!-- 透明的文件输入框覆盖层 -->
                        <input type="file" id="staticAvatarInput" accept="image/*" 
                               style="position: absolute; top: 0; left: 0; width: 120px; height: 120px; 
                               border-radius: 50%; opacity: 0; cursor: pointer; z-index: 10;">
                    </div>
                                         <p style="margin-top: 15px; color: #666; font-size: 12px;">
                         <i class="layui-icon layui-icon-upload" style="margin-right: 3px;"></i>
                         点击头像可更换
                     </p>
                </div>
            </div>

            <!-- 账户信息 -->
            <div class="widget">
                <div class="widget-header">
                    <h2 class="widget-title">账户信息</h2>
                </div>
                <div class="layui-row">
                    <div class="layui-col-xs12">
                        <div style="padding: 10px 0; border-bottom: 1px solid #f0f0f0;">
                            <div style="color: #666; font-size: 12px;">最后登录时间</div>
                            <div id="lastLoginTime" style="font-weight: 600; margin-top: 5px;">-</div>
                        </div>
                        <div style="padding: 10px 0;">
                            <div style="color: #666; font-size: 12px;">注册时间</div>
                            <div id="createdAt" style="font-weight: 600; margin-top: 5px;">-</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 快捷操作 -->
            <div class="widget">
                <div class="widget-header">
                    <h2 class="widget-title">快捷操作</h2>
                </div>
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-xs12">
                        <a href="/admin/settings/changePassword" class="layui-btn layui-btn-fluid layui-btn-primary">
                            <i class="layui-icon layui-icon-password"></i> 修改密码
                        </a>
                    </div>
                    <div class="layui-col-xs12" style="margin-top: 10px;">
                        <a href="/admin/settings/basic" class="layui-btn layui-btn-fluid layui-btn-primary">
                            <i class="layui-icon layui-icon-set"></i> 系统设置
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
layui.use(['form', 'layer'], function(){
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery;
    
    var isEditing = false;
    
    // 上传状态标记，防止重复上传
    var isUploading = false;
    var lastUploadTime = 0;
    var lastUploadFileInfo = null;
    
    // 加载个人信息
    function loadProfile() {
        $.ajax({
            url: '/admin/settings/getProfile',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.code === 0) {
                    var data = res.data;
                    form.val('profileForm', {
                        username: data.username,
                        real_name: data.real_name || '',
                        email: data.email || '',
                        phone: data.phone || '',
                        department: data.department || '',
                        position: data.position || '',
                        role_names: data.role_names || '无'
                    });
                    
                    // 更新头像
                    if (data.avatar && data.avatar !== '/static/images/default-avatar.svg') {
                        $('#userAvatar').attr('src', data.avatar);
                    } else {
                        $('#userAvatar').attr('src', '/static/images/default-avatar.svg');
                    }
                    
                    // 更新账户信息
                    $('#lastLoginTime').text(data.last_login_time || '从未登录');
                    $('#createdAt').text(data.created_at || '-');
                } else {
                    layer.msg(res.msg || '加载个人信息失败', {icon: 2});
                }
            },
            error: function() {
                layer.msg('网络错误，请稍后重试', {icon: 2});
            }
        });
    }
    
    // 切换编辑模式
    function toggleEditMode() {
        isEditing = !isEditing;
        
        if (isEditing) {
            // 进入编辑模式
            $('#profileForm input[name!="username"][name!="role_names"]').removeClass('layui-disabled').removeAttr('readonly');
            $('#editBtn').html('<i class="layui-icon layui-icon-close"></i> 取消编辑');
            $('#actionButtons').show();
        } else {
            // 退出编辑模式
            $('#profileForm input').addClass('layui-disabled').attr('readonly', 'readonly');
            $('#editBtn').html('<i class="layui-icon layui-icon-edit"></i> 编辑信息');
            $('#actionButtons').hide();
            // 重新加载数据，撤销未保存的修改
            loadProfile();
        }
    }
    
    // 编辑按钮事件
    $('#editBtn').click(function() {
        toggleEditMode();
    });
    
    // 取消按钮事件
    $('#cancelBtn').click(function() {
        toggleEditMode();
    });
    
    // 头像悬停效果
    $('.avatar-container').hover(
        function() {
            $(this).find('.avatar-overlay').css('display', 'flex');
        },
        function() {
            $(this).find('.avatar-overlay').hide();
        }
    );
    
    // 文件选择change事件
    $('#staticAvatarInput').off('change').on('change', function(e) {
        var file = e.target.files[0];
        if (!file) {
            return;
        }
        
        // 防止重复上传
        if (isUploading) {
            layer.msg('正在上传中，请稍候...', {icon: 0});
            this.value = '';
            return;
        }
        
        // 立即设置上传状态
        isUploading = true;
        
        // 检查文件类型
        if (!file.type.match('image.*')) {
            layer.msg('请选择图片文件', {icon: 2});
            isUploading = false;
            this.value = '';
            return;
        }
        
        // 检查文件大小（1MB）
        if (file.size > 1024 * 1024) {
            layer.msg('图片大小不能超过1MB', {icon: 2});
            isUploading = false;
            this.value = '';
            return;
        }
        
        // 检查是否是重复文件
        var currentTime = Date.now();
        var currentFileInfo = file.name + '_' + file.size + '_' + file.lastModified;
        
        if (currentTime - lastUploadTime < 3000 && currentFileInfo === lastUploadFileInfo) {
            layer.msg('请勿重复上传相同文件', {icon: 0});
            isUploading = false;
            this.value = '';
            return;
        }
        
        lastUploadTime = currentTime;
        lastUploadFileInfo = currentFileInfo;
        
        // 上传头像
        uploadAvatar(file);
        
        // 清空文件选择器，允许重复选择同一文件
        this.value = '';
    });
    
    // 表单提交
    form.on('submit(updateProfile)', function(data) {
        var loadIndex = layer.load(2);
        
        $.ajax({
            url: '/admin/settings/updateProfile',
            type: 'POST',
            data: data.field,
            dataType: 'json',
            success: function(res) {
                layer.close(loadIndex);
                if (res.code === 0) {
                    layer.msg(res.msg || '更新成功', {icon: 1});
                    toggleEditMode(); // 退出编辑模式
                    loadProfile(); // 重新加载数据
                } else {
                    layer.msg(res.msg || '更新失败', {icon: 2});
                }
            },
            error: function() {
                layer.close(loadIndex);
                layer.msg('网络错误，请稍后重试', {icon: 2});
            }
        });
        
        return false;
    });
    
    // 上传头像函数
    function uploadAvatar(file) {
        var formData = new FormData();
        formData.append('avatar', file);
        
        var loadIndex = layer.load(2, {content: '上传中...'});
        
        $.ajax({
            url: '/admin/settings/uploadAvatar',
            type: 'POST',
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            timeout: 30000, // 30秒超时
            success: function(res) {
                layer.close(loadIndex);
                isUploading = false;
                
                if (res.code === 0) {
                    layer.msg(res.msg || '头像上传成功', {icon: 1});
                    // 更新头像显示，优先使用缩略图
                    var displayUrl = res.data.thumb || res.data.url;
                    $('#userAvatar').attr('src', displayUrl + '?t=' + Date.now());
                } else {
                    layer.msg(res.msg || '上传失败', {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                isUploading = false;
                
                if (xhr.status === 413) {
                    layer.msg('文件太大，请选择1MB以下的图片', {icon: 2});
                } else if (status === 'timeout') {
                    layer.msg('上传超时，请稍后重试', {icon: 2});
                } else {
                    layer.msg('网络错误，请稍后重试', {icon: 2});
                }
            }
        });
    }
    
    // 页面加载时获取个人信息
    loadProfile();
});
</script>

<style>
.widget {
    transition: all 0.3s ease;
}

.widget:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.layui-form-label {
    font-weight: 600;
    color: #333;
}

.layui-input:focus {
    border-color: #1890ff !important;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.avatar-container .avatar-overlay {
    transition: all 0.3s ease;
}

.btn-widget {
    transition: all 0.2s ease;
}

.btn-widget:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

/* 移动端适配 */
@media (max-width: 768px) {
    .layui-col-md4, .layui-col-md6, .layui-col-md8, .layui-col-md12 {
        width: 100% !important;
        margin-bottom: 15px;
    }
    
    .page-header {
        text-align: center;
    }
    
    .widget-header {
        flex-direction: column;
        text-align: center;
    }
    
    .widget-actions {
        margin-top: 10px;
        width: 100%;
    }
    
    .btn-widget {
        width: 100%;
    }
}
</style>

{include file="layout/layui_footer" /} 